package top.lywivan.complexity;

import java.util.HashSet;
import java.util.Set;

class Trie {

    TreeNode root;

    public Trie() {
        this.root=new TreeNode();
    }
    
    public void insert(String word) {
        char[] chs=word.toCharArray();
        TreeNode curr=root;
        for(char ch:chs){
            if(curr.childs[ch-'a']==null){
                curr.addChild(ch);
            }
            curr=curr.childs[ch-'a'];
        }
        curr.isEnd=true;
    }
    
    public boolean search(String word) {
        TreeNode node=getTreeNode(word);
        return node!=null&&node.isEnd;
    }

    public TreeNode getTreeNode(String word){
        char[] chs=word.toCharArray();
        TreeNode curr=root;
        for(char ch:chs){
            if(curr.childs[ch-'a']==null){
                return null;
            }
            curr=curr.childs[ch-'a'];
        }
        return curr;
    }
    
    public boolean startsWith(String prefix) {
        TreeNode node=getTreeNode(prefix);
        return node!=null;
    }
}

class TreeNode{
    public final int R=26;
    public TreeNode[] childs;
    public boolean isEnd;

    public TreeNode(){
        this.childs=new TreeNode[26];
    }

    public boolean containsChild(char c){
        return childs[c-'a']!=null;
    }

    public void addChild(char c){
        childs[c-'a']=new TreeNode();
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */